"""
右侧预览面板模块
负责显示颜色预览、颜色信息和颜色选择器
"""

from PySide6.QtWidgets import (QWidget, QVBoxLayout, QLabel, QFrame, 
                             QHBoxLayout, QSlider, QSpinBox, QPushButton,
                             QColorDialog, QLineEdit)
from PySide6.QtCore import Qt, Signal
from PySide6.QtGui import QPixmap, QImage, QColor

from ...config.settings import AppConfig


class PreviewPanel(QWidget):
    """右侧预览面板"""
    
    color_changed = Signal(str)  # 颜色改变信号
    
    def __init__(self):
        super().__init__()
        self.current_preview = None
        self.current_color = "#FFFFFF"
        self._setup_ui()
    
    def _setup_ui(self):
        """设置UI界面"""
        layout = QVBoxLayout(self)
        
        # 预览标签
        layout.addWidget(QLabel("颜色预览:"))
        
        # 预览区域
        self.preview_label = QLabel()
        self.preview_label.setMinimumSize(200, 200)
        self.preview_label.setAlignment(Qt.AlignCenter)
        self.preview_label.setFrameShape(QFrame.Box)
        self.preview_label.setStyleSheet("QLabel { border: 2px solid #CCCCCC; }")
        layout.addWidget(self.preview_label)
        
        # 颜色信息
        self.color_info_label = QLabel()
        self.color_info_label.setAlignment(Qt.AlignCenter)
        layout.addWidget(self.color_info_label)
        
        # 颜色选择器
        self._setup_color_selector(layout)
        
        layout.addStretch()
    
    def update_preview(self, pil_image, hex_color, rgb_values):
        """
        更新预览
        
        Args:
            pil_image: PIL图片对象
            hex_color (str): 16进制颜色值
            rgb_values (tuple): RGB值元组 (R, G, B)
        """
        try:
            # 转换为QPixmap
            qimage = self._pil_to_qimage(pil_image)
            pixmap = QPixmap.fromImage(qimage)
            
            # 更新预览标签
            self.preview_label.setPixmap(pixmap)
            
            # 更新颜色信息
            r, g, b = rgb_values
            self.color_info_label.setText(
                f"颜色: {hex_color}\n"
                f"RGB: ({r}, {g}, {b})"
            )
            
        except Exception as e:
            self.color_info_label.setText(f"预览错误: {str(e)}")
    
    def _pil_to_qimage(self, pil_image) -> QImage:
        """
        PIL图片转QImage
        
        Args:
            pil_image: PIL图片对象
            
        Returns:
            QImage: Qt图片对象
        """
        if pil_image.mode == "RGB":
            r, g, b = pil_image.split()
            pil_image = pil_image.convert("RGB")
        elif pil_image.mode == "RGBA":
            r, g, b, a = pil_image.split()
            pil_image = pil_image.convert("RGBA")
        
        # 转换为QImage
        data = pil_image.tobytes()
        width, height = pil_image.size
        
        if pil_image.mode == "RGB":
            return QImage(data, width, height, width * 3, QImage.Format_RGB888)
        else:  # RGBA
            return QImage(data, width, height, width * 4, QImage.Format_RGBA8888)
    
    def _setup_color_selector(self, parent_layout):
        """设置颜色选择器"""
        # 颜色选择器标签
        parent_layout.addWidget(QLabel("颜色选择器:"))
        
        # 颜色预览框
        color_preview_layout = QHBoxLayout()
        self.color_preview_box = QLabel()
        self.color_preview_box.setFixedSize(50, 30)
        self.color_preview_box.setFrameShape(QFrame.Box)
        self.color_preview_box.setStyleSheet(f"background-color: {self.current_color}")
        color_preview_layout.addWidget(self.color_preview_box)
        
        # 颜色值输入框
        self.hex_input = QLineEdit(self.current_color)
        self.hex_input.setFixedWidth(80)
        self.hex_input.textChanged.connect(self._on_hex_changed)
        color_preview_layout.addWidget(self.hex_input)
        
        # 调色板按钮
        self.color_picker_btn = QPushButton("调色板")
        self.color_picker_btn.clicked.connect(self._open_color_picker)
        color_preview_layout.addWidget(self.color_picker_btn)
        
        parent_layout.addLayout(color_preview_layout)
        
        # RGB滑块
        self._setup_rgb_sliders(parent_layout)
    
    def _setup_rgb_sliders(self, parent_layout):
        """设置RGB滑块"""
        # 红色滑块
        red_layout = QHBoxLayout()
        red_layout.addWidget(QLabel("R:"))
        self.red_slider = QSlider(Qt.Horizontal)
        self.red_slider.setRange(0, 255)
        self.red_slider.valueChanged.connect(self._on_rgb_changed)
        self.red_spin = QSpinBox()
        self.red_spin.setRange(0, 255)
        self.red_spin.valueChanged.connect(self._on_spin_changed)
        red_layout.addWidget(self.red_slider)
        red_layout.addWidget(self.red_spin)
        parent_layout.addLayout(red_layout)
        
        # 绿色滑块
        green_layout = QHBoxLayout()
        green_layout.addWidget(QLabel("G:"))
        self.green_slider = QSlider(Qt.Horizontal)
        self.green_slider.setRange(0, 255)
        self.green_slider.valueChanged.connect(self._on_rgb_changed)
        self.green_spin = QSpinBox()
        self.green_spin.setRange(0, 255)
        self.green_spin.valueChanged.connect(self._on_spin_changed)
        green_layout.addWidget(self.green_slider)
        green_layout.addWidget(self.green_spin)
        parent_layout.addLayout(green_layout)
        
        # 蓝色滑块
        blue_layout = QHBoxLayout()
        blue_layout.addWidget(QLabel("B:"))
        self.blue_slider = QSlider(Qt.Horizontal)
        self.blue_slider.setRange(0, 255)
        self.blue_slider.valueChanged.connect(self._on_rgb_changed)
        self.blue_spin = QSpinBox()
        self.blue_spin.setRange(0, 255)
        self.blue_spin.valueChanged.connect(self._on_spin_changed)
        blue_layout.addWidget(self.blue_slider)
        blue_layout.addWidget(self.blue_spin)
        parent_layout.addLayout(blue_layout)
        
        # 初始化RGB值
        self._update_rgb_from_hex(self.current_color)
    
    def _on_hex_changed(self, hex_text):
        """16进制输入改变"""
        if len(hex_text) == 7 and hex_text.startswith('#'):
            try:
                self.current_color = hex_text.upper()
                self.color_preview_box.setStyleSheet(f"background-color: {self.current_color}")
                self._update_rgb_from_hex(hex_text)
                self.color_changed.emit(self.current_color)
            except:
                pass
    
    def _on_rgb_changed(self):
        """RGB滑块改变"""
        r = self.red_slider.value()
        g = self.green_slider.value()
        b = self.blue_slider.value()
        
        hex_color = f"#{r:02X}{g:02X}{b:02X}"
        self.current_color = hex_color
        self.hex_input.setText(hex_color)
        self.color_preview_box.setStyleSheet(f"background-color: {hex_color}")
        self.color_changed.emit(hex_color)
    
    def _on_spin_changed(self):
        """数值框改变"""
        self.red_slider.setValue(self.red_spin.value())
        self.green_slider.setValue(self.green_spin.value())
        self.blue_slider.setValue(self.blue_spin.value())
    
    def _update_rgb_from_hex(self, hex_color):
        """从16进制更新RGB值"""
        if len(hex_color) == 7 and hex_color.startswith('#'):
            try:
                r = int(hex_color[1:3], 16)
                g = int(hex_color[3:5], 16)
                b = int(hex_color[5:7], 16)
                
                self.red_slider.setValue(r)
                self.green_slider.setValue(g)
                self.blue_slider.setValue(b)
                self.red_spin.setValue(r)
                self.green_spin.setValue(g)
                self.blue_spin.setValue(b)
            except:
                pass
    
    def _open_color_picker(self):
        """打开颜色选择器"""
        color = QColorDialog.getColor(QColor(self.current_color))
        if color.isValid():
            hex_color = color.name().upper()
            self.current_color = hex_color
            self.hex_input.setText(hex_color)
            self.color_preview_box.setStyleSheet(f"background-color: {hex_color}")
            self._update_rgb_from_hex(hex_color)
            self.color_changed.emit(hex_color)
    
    def set_color(self, hex_color):
        """设置颜色"""
        if len(hex_color) == 7 and hex_color.startswith('#'):
            self.current_color = hex_color.upper()
            self.hex_input.setText(hex_color)
            self.color_preview_box.setStyleSheet(f"background-color: {hex_color}")
            self._update_rgb_from_hex(hex_color)
    
    def get_color(self):
        """获取当前颜色"""
        return self.current_color
    
    def clear_preview(self):
        """清除预览"""
        self.preview_label.clear()
        self.color_info_label.clear()